package com.zxjbyte.yiyi.module.plugin.sse.service.impl;

import com.zxjbyte.yiyi.framework.common.constant.HeaderMsg;
import com.zxjbyte.yiyi.framework.common.domain.message.StreamMessage;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import com.zxjbyte.yiyi.module.plugin.sse.processor.SseEmitterCallBackProcessor;
import com.zxjbyte.yiyi.module.plugin.sse.service.SseEmitterService;
import com.zxjbyte.yiyi.module.plugin.sse.session.SseSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Objects;

/**
 * @Author zhangxingjia
 * @Date 2024/6/24 17:50
 * @Version: 1.0
 */
@Slf4j
@Service
public class SseEmitterServiceImpl implements SseEmitterService {

    @Override
    public SseEmitter createConnect(String clientId, Boolean openHeartBeat) {
        String userId = AuthUtil.getUserIdAsStr();
        SseEmitter sseEmitter = SseSession.getSseEmitter(clientId, userId);
        if(Objects.nonNull(sseEmitter)){
            return sseEmitter;
        }
        // 设置为0L时永不超时
        sseEmitter = new SseEmitter(0L);
        // 增加连接
        SseSession.addConnection(clientId, userId, sseEmitter, openHeartBeat);
        // 处理回调
        SseEmitterCallBackProcessor.createCallBack(sseEmitter, clientId, userId);
        // 发送一条连接成功的消息
        SseSession.sendMessage(clientId, userId, "用户[" + userId +"]连接成功啦！");
        return sseEmitter;
    }

    @Override
    public void closeConnect(String clientId) {
        String userId = AuthUtil.getUserIdAsStr();
        SseSession.removeConnection(clientId, userId);
    }

    @Override
    public void broadcast(String clientId, String message) {
        SseSession.broadcastMessage(clientId, StreamMessage.of(HeaderMsg.BROADCAST_MESSAGE, message));
    }

    @Override
    public void sendOne(String clientId, String message) {
        String userId = AuthUtil.getUserIdAsStr();
        SseSession.sendMessage(clientId, userId, StreamMessage.of(HeaderMsg.SEND_MESSAGE, message));
    }
}
